import {onMounted, ref, onUnmounted} from "vue";
import DEFAULT_CONFIG from "@/config/index.js";

export function createAgentAi(){
    //websocket
    let ws = ref({})
    const connected = ref(false)
    const loading = ref(false)
    const agentModel = ref("")
    let reconnectTimer = null
    let reconnectAttempts = 0
    const maxReconnectAttempts = 5
    const reconnectDelay = 3000

    const messages = ref([
        {
            id: Date.now(),
            role: 'assistant', 
            content: '你好！我是AI助手,有什么可以帮你的吗?',
            timestamp: Date.now()
        }
    ])

    // 获取AI配置
    const getAiConfig = () => {
        try {
            const aiSettings = localStorage.getItem('aiSettings')
            if (aiSettings) {
                return JSON.parse(aiSettings)
            }
        } catch (error) {
            console.error('加载AI设置失败:', error)
        }
        return null
    }

    // 获取WebSocket地址
    const getWebSocketUrl = () => {
        const config = getAiConfig()
        return config?.aiUrl || DEFAULT_CONFIG.AI_URL
    }

    // 初始化WebSocket连接
    const initWebSocket = () => {
        const url = getWebSocketUrl()
        console.log('正在连接到WebSocket:', url)
        
        try {
            ws.value = new WebSocket(url)

            ws.value.onopen = () => {
                console.log("WebSocket连接成功")
                connected.value = true
                reconnectAttempts = 0
                if (loading.value) {
                    loading.value = false
                }
            }

            ws.value.onclose = (event) => {
                console.log("WebSocket连接关闭", event.code, event.reason)
                connected.value = false
                
                // 如果不是主动关闭，尝试重连
                if (event.code !== 1000 && reconnectAttempts < maxReconnectAttempts) {
                    scheduleReconnect()
                }
            }

            ws.value.onerror = (error) => {
                console.error("WebSocket错误:", error)
                connected.value = false
                if (loading.value) {
                    loading.value = false
                }
            }

            ws.value.onmessage = receiveMessage;
        } catch (error) {
            console.error("WebSocket创建失败:", error)
            connected.value = false
            if (loading.value) {
                loading.value = false
            }
        }
    }

    // 调度重连
    const scheduleReconnect = () => {
        if (reconnectTimer) {
            clearTimeout(reconnectTimer)
        }
        
        reconnectAttempts++
        reconnectTimer = setTimeout(() => {
            console.log(`尝试重连 (${reconnectAttempts}/${maxReconnectAttempts})...`)
            initWebSocket()
        }, reconnectDelay * reconnectAttempts) // 指数退避
    }

    onMounted(() => {
        initWebSocket()
    })

    onUnmounted(() => {
        if (reconnectTimer) {
            clearTimeout(reconnectTimer)
        }
        if (ws.value) {
            ws.value.close(1000, '组件卸载')
        }
    })

    //发送消息
    const sendMessage = (message) => {
        if (!message || !message.trim()) {
            return
        }

        if (!ws.value || ws.value.readyState !== WebSocket.OPEN) {
            console.warn("WebSocket未连接，尝试重新连接...")
            initWebSocket()
            setTimeout(() => {
                if (ws.value && ws.value.readyState === WebSocket.OPEN) {
                    sendMessage(message)
                } else {
                    console.error("连接失败，无法发送消息")
                }
            }, 1000)
            return
        }

        // 先添加用户消息到消息列表
        messages.value.push({
            id: Date.now(),
            role: 'user',
            content: message.trim(),
            timestamp: Date.now()
        })

        // 设置加载状态
        loading.value = true

        // 根据配置选择是否使用模型
        const config = getAiConfig()
        const useModel = config?.aiModel && config.aiModel.length > 5
        
        if (useModel || agentModel.value !== '' && agentModel.value.length > 5) {
            const model = config?.aiModel || agentModel.value
            let ms = [];
            const msg = {
                role: 'user',
                content: message.trim()
            }
            ms.push(msg);

            let obj = {
                type: 'prompt',
                message: JSON.stringify(ms),
            }

            ws.value.send(JSON.stringify(obj));
        } else {
            const msg = {
                type: 'prompt',
                message: message.trim()
            }
            ws.value.send(JSON.stringify(msg))
        }
    }
    const isLastMessageAssistant = () => {
        return messages.value.length > 0 &&
            messages.value[messages.value.length - 1].role === 'assistant'
    }

// 辅助函数：检查最后一条消息是否是推理消息
    const isLastMessageReasoning = () => {
        return messages.value.length > 0 &&
            messages.value[messages.value.length - 1].role === 'reasoning'
    }
    //接收消息处理
    const receiveMessage=(event)=>{
        let message = ''
        const msg = JSON.parse(event.data)

        if (msg.messageType === 'content' ) {
            if(msg.content===""){
                return;
            }
            if (isLastMessageAssistant()) {
                // 如果最后一条是助手消息，追加内容
                const lastMsg = messages.value[messages.value.length - 1]
                lastMsg.content += msg.content || ''
            } else {
                // 否则创建新的助手消息
                messages.value.push({
                    id: Date.now(),
                    role: 'assistant',
                    content: msg.content || '',
                    timestamp: Date.now()
                })
            }
        }
        else if (msg.messageType === 'reasoning') {
            if(msg.content===""){
                return;
            }
            if (isLastMessageReasoning()) {
                // 如果最后一条是助手消息，追加内容
                const lastMsg = messages.value[messages.value.length - 1]
                lastMsg.content += msg.content || ''
            } else {
                // 否则创建新的助手消息
                messages.value.push({
                    id: Date.now(),
                    role: 'reasoning',
                    content: msg.content || '',
                    timestamp: Date.now()
                })
            }
        }
        else if (msg.messageType === 'over') {
            loading.value = false
        }
        else if (msg.messageType === 'error') {
            loading.value = false
            // 添加错误消息
            messages.value.push({
                id: Date.now(),
                role: 'assistant',
                content: `错误：${msg.error || '未知错误'}`,
                timestamp: Date.now(),
                isError: true
            })
        }
        else if (msg.messageType === 'system') {
            // 系统消息可以用于显示连接状态、提示等信息
        }
    }

    // 清空消息历史
    const clearMessages = () => {
        messages.value = [{
            id: Date.now(),
            role: 'assistant',
            content: '你好！我是AI助手,有什么可以帮你的吗?',
            timestamp: Date.now()
        }]
    }

    // 删除指定消息
    const deleteMessage = (messageId) => {
        messages.value = messages.value.filter(msg => msg.id !== messageId)
    }

    // 重新发送消息
    const resendMessage = (messageId) => {
        const message = messages.value.find(msg => msg.id === messageId)
        if (message && message.role === 'user') {
            // 删除该消息及其后的所有消息
            const index = messages.value.findIndex(msg => msg.id === messageId)
            if (index !== -1) {
                messages.value = messages.value.slice(0, index)
                // 重新发送
                sendMessage(message.content)
            }
        }
    }

    // 导出对话历史
    const exportHistory = () => {
        return JSON.stringify(messages.value, null, 2)
    }

    // 导入对话历史
    const importHistory = (historyJson) => {
        try {
            const history = JSON.parse(historyJson)
            if (Array.isArray(history)) {
                messages.value = history
            }
        } catch (error) {
            console.error('导入历史失败:', error)
            throw error
        }
    }

    // 获取消息统计
    const getMessageStats = () => {
        const stats = {
            total: messages.value.length,
            user: messages.value.filter(msg => msg.role === 'user').length,
            assistant: messages.value.filter(msg => msg.role === 'assistant').length,
            reasoning: messages.value.filter(msg => msg.role === 'reasoning').length
        }
        return stats
    }

    // 手动重连
    const reconnect = () => {
        console.log("手动重连...")
        if (ws.value) {
            ws.value.close()
        }
        reconnectAttempts = 0
        initWebSocket()
    }

    // 获取连接状态
    const getConnectionStatus = () => {
        if (!ws.value) return 'disconnected'
        switch (ws.value.readyState) {
            case WebSocket.CONNECTING: return 'connecting'
            case WebSocket.OPEN: return 'connected'
            case WebSocket.CLOSING: return 'closing'
            case WebSocket.CLOSED: return 'disconnected'
            default: return 'unknown'
        }
    }

    return {
        ws,
        sendMessage,
        agentModel,
        connected,
        messages,
        loading,
        reconnect,
        getConnectionStatus,
        clearMessages,
        deleteMessage,
        resendMessage,
        exportHistory,
        importHistory,
        getMessageStats
    }
}
